package com.free.mini.study.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志打印
 */
@Aspect
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestLogAdvice {

    @Autowired
    private HttpServletRequest request;

    @Pointcut("execution(* com.free.mini.study.controller.*.*(..))")
    private void webLog() {
    }

    @Around("webLog()")
    public Object interception(ProceedingJoinPoint joinPoint) throws Throwable {
        String uri = request.getRequestURI();
        StringBuilder logMsg = new StringBuilder(uri);
        if (joinPoint.getArgs().length > 0) {
            logMsg.append(" @Request");
            for (Object arguments : joinPoint.getArgs()) {
                logMsg.append(" ").append(arguments);
            }
        }
        log.info("req : {}",logMsg);
        logMsg = new StringBuilder(uri);
        long start = System.currentTimeMillis();
        try {
            Object value = joinPoint.proceed();
            if (value != null) {
                logMsg.append(" @Response ").append(value);
            }
            return value;
        } catch (Exception e) {
            logMsg.append(" @Error msg=").append(e.getMessage());
            throw e;
        } finally {
            logMsg.append(" Cost=");
            long end = System.currentTimeMillis();
            logMsg.append(" @Time ").append(end - start);
            log.info("resp : {}",logMsg);
        }
    }

}

